const { ipcRenderer } = require("electron");
const path = require("path");

Lyx.require(["vue", "ajax"], Vue => {

    let watch = {
        keyWord: function (keyWord) {
            this.index = -1;
            ipcRenderer.send("keyWord", keyWord);
        }
    };

    let saveSetting = {
        alias: () => {
            return search.settingCache.alias.filter(i => i.alias != "" && i.path != "");
        },
        dirPathList: () => {
            return search.settingCache.dirPathList.filter(i => i != "");
        },
        extensions: () => {
            return search.settingCache.extensions.filter(i => i != "");
        },
        filter: () => {
            return search.settingCache.filter.filter(i => i != "");
        }
    }

    for (let key of ipcRenderer.sendSync("getSettingKey")) {
        watch[`setting.${ key }`] = (value) => {
            if (saveSetting[key]) {
                value = saveSetting[key](value);
            }
            ipcRenderer.send("saveSetting", key, value);
        };
    }

    const search = new Vue({
        el: "#app",
        data: {
            keyWord: "",
            list: [],
            lastUpdate: "",
            consume: 0,
            index: -1,
            cache: [],
            alias: [],
            fileNameWidth: 300,
            aliasPath: "",
            setAliasLock: false,
            setting: ipcRenderer.sendSync("getSetting"),
            settingCache: ipcRenderer.sendSync("getSetting")
        },
        methods: {
            openSelect() {
                ui.css("#open", {
                    background: "rgba(0, 0, 0, 0.7)",
                    zIndex: 99999
                });
                $("#open div[0]").innerHTML = "启动中&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                let runing = Lyx.interval(function () {
                    $("#open div[0]").innerHTML = "启动中" + "·".repeat(this.number % 5) + "&nbsp;".repeat(5 - this.number % 5);
                }, 300);
                ipcRenderer.send("open", this.list[Lyx.scope(0, this.list.length - 1, this.index)]);
                ipcRenderer.once("open", (event, success) => {
                    $("#open div[0]").innerHTML = `启动${ success ? "成功" : "失败" }!&nbsp;&nbsp;&nbsp;&nbsp;`;
                    runing.stop();
                    if (success) {
                        ui.css("#open", {
                            background: "rgba(0, 0, 0, 0)",
                            zIndex: -99999
                        });
                    }
                });
            },
            up() {
                this.index = Lyx.scope(0, this.list.length - 1, this.index - 1);
                if (this.index < parseInt(result.y / 40) + 1) {
                    result.y -= 40;
                }
            },
            down() {
                this.index = Lyx.scope(0, this.list.length - 1, this.index + 1);
                if (this.index > 12) {
                    result.y += 40;
                }
            },
            setAlias(event) {
                if (!this.setAliasLock) {
                    this.setAliasLock = true;
                    this.settingCache.alias.push({
                        alias: event.target.value,
                        path: this.aliasPath
                    });
                    this.setting.alias = !this.setting.alias;
                }
            }
        },
        watch: watch,
        mounted: main
    });

    Lyx.extendGlobal("search", search);
});

function main() {
    ipcRenderer.send("keyWord", search.keyWord || "");
    Lyx.require(["scroll", "drag", "alert"], (Scroll, Drag, Alert) => {
        // 主界面滚动
        Lyx.extendGlobal("result", new Scroll("#result", {
            height: 560,
            width: 1000,
            ySpeed: 80,
            yBarWidth: 3,
            yBarSwitch: true,
            dragSwitch: false,
            onBottom: () => {
                // 触底时，添加条数
                search.list = search.cache.slice(0, search.list.length + 20);
            }
        }));

        // 设置区域滚动
        Scroll("#settingList", {
            height: 570,
            width: 300,
            dragSwitch: false
        });

        // 查询结果鼠标移入效果
        ui.hander.add("#result", "mouseover", event => {
            if (event.target.nodeName == 'DIV') {
                this.index = parseInt(event.target.parentNode.getAttribute("name"));
            }
        });

        // 点击菜单按钮
        ui.hander.add("#menuButton", "click", () => {
            ui.css("#setting", {
                transform: "translateX(300px)",
                boxShadow: "0 2px 8px rgba(0,0,0,.8)"
            });

            ui.css("#settingBack", {
                background: "rgba(0, 0, 0, 0.5)",
                zIndex: 99998
            });
        });

        // 菜单打开时，点击空白收起菜单
        ui.hander.add("#settingBack", "click", () => {
            ui.css("#setting", {
                transform: "translateX(0)",
                boxShadow: "0 2px 8px rgba(0,0,0,0)"
            });

            ui.css("#settingBack", {
                background: "rgba(0, 0, 0, 0)",
                zIndex: -1
            });
        });

        ui.hander.add("#open", "click", () => {
            ui.css("#open", {
                background: "rgba(0, 0, 0, 0)",
                zIndex: -1
            });
        })

        // 双击打开
        ui.hander.add("#result", "dblclick", event => {
            if (event.target.parentNode.nodeName == "LI") {
                search.openSelect();
            }
        });

        // 拖动分界线
        Drag("#vertical", {
            move: drag => {
                drag.style.top = drag.top;
                drag.style.left = Lyx.scope(100, 800, drag.style.left);
                search.fileNameWidth = drag.style.left - 20;
            }
        });

        // 下拉刷新
        Lyx.extendGlobal("refresh", new Drag("#result", {
            down: drag => {
                drag.style.transition = "";
                ui.css("#line", { transition: "" });
                ui.css("#refresh", { transition: ""});
                ui.css("#refreshImg", { animation: "" });
            },
            move: drag => {
                drag.style.left = drag.left;
                drag.style.top = Lyx.scope(0, 550, drag.top + drag.offsetY / 1.5);
                ui.css("#line", { top: drag.style.top + 50 });
                ui.css("#refresh", { top:  Lyx.scope(0, 60, drag.style.top - 15) });
                ui.css("#refreshImg", { transform: `rotate(${-drag.style.top * 10}deg)` });
            },
            up: drag => {
                drag.style.transition = ".3s";
                ui.css("#line", { transition: ".3s" });
                if (drag.style.top >= 75) {
                    drag.style.top = 75;
                    ui.css("#line", { top: 125 });
                    ui.css("#refreshImg", { animation: "refreshImg 1s linear infinite" });
                    ipcRenderer.send("refresh");
                }
                else {
                    drag.style.top = 0;
                    recoverRefresh();
                }
            }
        }));

        // 关闭程序
        ui.hander.add("#close", "click", () => {
            ipcRenderer.sendSync("close");
        });

        // 隐藏设置别名窗口
        ui.hander.add("#setAliasBack", "click", () => {
            ui.css("#setAliasWindow", {
                "offset-top": 50,
                opacity: 0,
                zIndex: -1
            });
            ui.css("#setAliasBack", { zIndex: -1 });
            ui.css("#aliasPath", { animation: "" });
        });

        Drag("#setAliasTitle", {
            up: (drag) => {
                drag.mappingStyle.transition = ".3s";
            },
            down: (drag) => {
                drag.mappingStyle.transition = "";
            },
            move: (drag) => {
                drag.mappingStyle.top = Lyx.scope(55, 505, drag.mappingStyle.top);
                drag.mappingStyle.left = Lyx.scope(5, 695, drag.mappingStyle.left);
            }
        }, {
            mappingEl: "#setAliasWindow",
            closeTarget: true
        });

        document.oncontextmenu = (event) => {
            let file = search.list[parseInt(event.target.parentNode.getAttribute("name"))];
            file.path = file.path.replace(/<[\s\S]*?>/g, '');
            file.name = file.name.replace(/<[\s\S]*?>/g, '');
            let menuList = [
                {
                    type: "copyName",
                    content: file.name
                },
                {
                    type: "copyPath",
                    content: file.path
                },
                {
                    type: "copyAll",
                    content: path.join(file.path, file.name)
                },
                {
                    type: "alias",
                    content: path.join(file.path, file.name)
                }
            ]
            ipcRenderer.send('show-context-menu', menuList);
        }

        function moveText(event) {
            if (event.target.style.animation == "pathMoveTextBegin 10s linear") {
                event.target.style.animation = "aliasMoveTextEnd 10s linear infinite";
            }
            if (event.target.style.animation == "aliasMoveTextBegin 5s linear") {
                event.target.style.animation = "aliasMoveTextEnd 5s linear infinite";
            }
            
        }

        ui.hander.add("#aliasDispaly", "mouseover", event => {
            if (event.target.getAttribute("name") == "path") {
                if (parseFloat(ui.getFinalStyle(event.target).width) > 200) {
                    event.target.style.animation = "pathMoveTextBegin 10s linear";
                    ui.hander.add(event.target, "animationend", moveText);
                }
            }
            if (event.target.getAttribute("name") == "alias") {
                if (parseFloat(ui.getFinalStyle(event.target).width) > 40) {
                    event.target.style.animation = "aliasMoveTextBegin 5s linear";
                    ui.hander.add(event.target, "animationend", moveText);
                }
            }
        });

        ui.hander.add("#aliasDispaly", "mouseout", event => {
            if (event.target.getAttribute("name") == "path") {
                event.target.style.animation = "";
                ui.hander.remove(event.target, "animationend", moveText);
            }
            if (event.target.getAttribute("name") == "alias") {
                event.target.style.animation = "";
                ui.hander.remove(event.target, "animationend", moveText);
            }
        });

        ui.hander.add("#aliasDispaly", "click", event => {
            if (event.target.getAttribute("name") == "close") {
                let index = parseInt(event.target.getAttribute("index"));
                search.settingCache.alias.splice(index, 1);
                this.setting.alias = !this.setting.alias;
            }
        });
    });
}

function recoverRefresh() {
    setTimeout(() => {
        ui.css("#refreshImg", {animation: "" });
        ui.css("#line", { top: 50 });
        refresh.style.top = 0;
        ui.css("#refresh", {
            transition: ".3s",
            top: 0
        });
    }, 300);
}

function ESC(event) {
    if (event.keyCode == 27) {
        ipcRenderer.send("esc");
    }
}

const settingCallback = {
    alias: () => {
        ui.css("#setAliasWindow", {
            "offset-top": 50,
            opacity: 0,
            zIndex: -1
        });
        ui.css("#setAliasBack", { zIndex: -1 });
        ui.css("#aliasPath", { animation: "" });
    }
};
const callback = {
    init: () => {
        search.keyWord = "";
        ui.css("#setting", {
            transform: "translateX(0)",
            boxShadow: "0 2px 8px rgba(0,0,0,0)"
        });

        ui.css("#settingBack", {
            background: "rgba(0, 0, 0, 0)",
            zIndex: -1
        });
    },
    setAlias: (path) => {
        search.setAliasLock = false;
        ui.css("#setAliasWindow", {
            transition: ".3s",
            zIndex: 3,
            opacity: 1,
            "offset-top": -50
        });
        ui.css("#setAliasBack", { zIndex: 2 });
        ui.css("#aliasPath", { animation: "moveText 10s linear infinite" });
        $("#alias").focus();
        $("#alias").value = "";
        search.aliasPath = path;
    },
    saveSetting: (key, value) => {
        if (settingCallback[key]) {
            settingCallback[key]();
        }
        if (["alias", "dirPathList", "extensions", "filter"].indexOf(key) != -1) {
            search.settingCache[key] = value;
        }
        else {
            search.setting[key] = value;
        }
        if (["highlight", "extensions", "filter"].indexOf(key) != -1) {
            ipcRenderer.send("keyWord", search.keyWord);
        }
    },
    alias: list => {
        list.forEach((file) => {
            file.alias = `<strong>${ file.alias }</strong>`
            search.cache.unshift(file);
            search.list.unshift(file);
        });
        search.list = search.cache.slice(0, 20);
    },
    focus: () => {
        $("#search").focus();
        ui.hander.add(document, "keyup", ESC);
    },
    blur: () => {
        ui.hander.remove(document, "keyup", ESC);
    },
    refresh: (consume, lastUpdate) => {
        result.toTop();
        result.update();
        search.consume = consume;
        search.lastUpdate = Lyx.format(new Date(lastUpdate), "yyyy-MM-dd hh:mm:ss");
        recoverRefresh();
        ipcRenderer.send("keyWord", search.keyWord);
    },
    keyWord:(list, consume, lastUpdate) => {
        search.consume = consume;
        search.lastUpdate = Lyx.format(new Date(lastUpdate), "yyyy-MM-dd hh:mm:ss");
        search.cache = list.sort((a, b) => {
            if (a.nameReg && !b.nameReg) return 1;
            if (!a.nameReg && b.nameReg) return -1;
            if (a.nameReg && b.nameReg) {
                return a.nameReg.length / a.name > b.nameReg.length / b.name ? 1 : -1;
            }
            return a.name > b.name ? 1 : -1;
        }).map((item) => {
            if (item.nameReg && item.nameReg != "") {
                item.name = item.name.replace(item.nameReg, `<span style="${search.setting.highlight}">${item.nameReg}</span>`);
            }
            if (item.pathReg && item.pathReg != "") {
                item.path = item.path.replace(item.pathReg, `<span style="${search.setting.highlight}">${item.pathReg}</span>`);
            }
            return item;
        });
        ipcRenderer.send("alias", search.keyWord);
        try {
            result.toTop();
            result.update();
        } catch (err) {}
    }
}

for (let type in callback) {
    ipcRenderer.on(type, function (event, ...args) {
        callback[type].apply(null, [...args, event]);
    });
}